/**
 * Created by three on 14-8-6.
 */
define(['angular', 'socket.io'], function (angular) {
    'use strict';

    /**
     * socket.io
     */
    angular.module('app.socket', [
        'app.func.config'
    ])
        .factory('socket', ['$rootScope', function ($rootScope) {
            var sockets = {};
            var socketsRegEvents = {};
            
            return function (scope, url) {
                var socket =  function (opts) {
                    if(!sockets[opts.url]) {
                        var socket = sockets[opts.url] = window.io.connect(opts.url);
                        socketsRegEvents[opts.url] = {};

                        socket.on('error', function (data) {
                            console.log('error')
                            console.log(data);
                        });
                        socket.on('reconnect_error', function (data) {
                            console.log('reconnect_error')
                            console.log(data);
                        });
                        socket.on('reconnect_failed', function (data) {
                            console.log('reconnect_failed')
                            console.log(data);
                        })
                    }
                    return sockets[opts.url];
                }({url:url});
                return {
                    on: function (event_name, callback) {
                        if(!socketsRegEvents[url][event_name]) {
                            socket.on(event_name, function () {
                                var args = arguments;
                                $rootScope.$apply(function () {
                                    $rootScope.$broadcast(url+event_name, {data:args});
                                });
                            });
                        }
                        socketsRegEvents[url][event_name] = true;
                        scope.$on(url+event_name, function (event, msg) {
                            callback.apply(socket, msg.data);
                        });
                    },
                    emit: function (event_name, data, callback) {
                        socket.emit(event_name, encodeURIComponent(data), function () {
                            var args = arguments;
                            $rootScope.$apply(function () {
                                if(callback) {
                                    callback.apply(socket, args)
                                }
                            });
                        });
                    }
                };
            };
            

        }])
    ;
});